package messwertrechner;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

/**
 * Main Class
 * 
 * @author Benedikt Markt
 * 
 */
public class Rechner {

	private static final String URL_STRING = "http://129.69.59.170/daten/data";
	private static Scanner fileScanner;
	private static Scanner cmdScanner;

	/**
	 * 
	 * @author Benedikt Markt
	 * 
	 * @param args
	 *            Command Line parameters
	 */
	public static void main(String[] args) {
		String in;
		int index = 0;
		System.out.println("Welche Messrinne soll ausgelesen werden?");
		in = getInput();
		try {
			index = Integer.parseInt(in);
		} catch (NumberFormatException e) {
			System.out.println("Ungültige Eingabe!");
			return;
		}
		System.out.println("Lese vom Server...");
		DataContainer container = getData(5);
		System.out.println("Gelesen!");
		container.zero();
		System.out.println("Schreibe Excel Datei...");
		container.writeToExcel("Data_" + index + ".xls");
		System.out.println("Abgeschlossen!");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static URL getDataUrl(int dataIndex) throws MalformedURLException {

		return new URL(URL_STRING + dataIndex + ".txt");
	}
	
	private static DataContainer getData(int dataIndex){
		fileScanner = null;
		DataContainer container = new DataContainer(dataIndex);
		try {
			URL dataUrl = getDataUrl(dataIndex);
			fileScanner = new Scanner(dataUrl.openStream());
			while (fileScanner.hasNextLine()) {
				container.addString(fileScanner.nextLine());
			}
		} catch (MalformedURLException e) {
			System.out.println("Ungültige URL!");
		} catch (ConnectException e) {
			System.out.println("Server nicht erreichbar!");
		} catch (IOException e) {
			System.out.println("Datei nicht lesbar!");
		} finally {
			fileScanner.close();
		}
		return container;
	}
	
	private static String getInput(){
		cmdScanner = null;
		cmdScanner = new Scanner(new InputStreamReader(System.in));
		return cmdScanner.nextLine();
	}

}
